#!/usr/bin/env bash
set -euo pipefail

open_url() {
  if command -v open >/dev/null 2>&1; then open "$1"
  elif command -v xdg-open >/dev/null 2>&1; then xdg-open "$1"
  fi
}

echo
echo "  Claude Code + DeepSeek"
echo "  ----------------------"
echo

# 1. Claude Code
if ! command -v claude >/dev/null 2>&1; then
  echo "Claude Code is not installed. Installing the official CLI..."
  curl -fsSL https://claude.ai/install.sh | bash
  export PATH="$HOME/.local/bin:$PATH"
  if ! command -v claude >/dev/null 2>&1; then
    echo "Install finished but 'claude' is not on PATH yet."
    echo "Open a new terminal and run this script again."
    exit 1
  fi
fi

# 1b. Optional: DeepSeek key and top-up pages
read -rp "Open DeepSeek in your browser to create a key or add credits? [y/N] " openweb
if [ "${openweb:-n}" = "y" ] || [ "${openweb:-n}" = "Y" ]; then
  open_url "https://platform.deepseek.com/api_keys"
  open_url "https://platform.deepseek.com/top_up"
  echo "Opened DeepSeek. Sign in, add credits, then create an API key (the key is separate from credits). Come back and paste it."
fi

# 2. Key
if [ -z "${DEEPSEEK_API_KEY:-}" ]; then
  read -rsp "Paste your DeepSeek API key (create one on the API keys page if you do not have one): " DEEPSEEK_API_KEY
  echo
fi
case "$DEEPSEEK_API_KEY" in
  sk-*) ;;
  *) echo "That does not look like a DeepSeek API key. It should start with sk-."; exit 1 ;;
esac
if [ "${#DEEPSEEK_API_KEY}" -lt 20 ]; then
  echo "That key is too short. Check it and rerun."
  exit 1
fi

# 3. Test
echo "Checking the key with DeepSeek..."
tmp="$(mktemp)"
code="$(curl -sS -o "$tmp" -w "%{http_code}" \
  https://api.deepseek.com/anthropic/v1/messages \
  -H "x-api-key: $DEEPSEEK_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{"model":"deepseek-v4-flash","max_tokens":8,"messages":[{"role":"user","content":"Reply with exactly: SETUP OK"}]}')" || true
if [ "$code" != "200" ]; then
  echo "DeepSeek rejected the key or the network failed (HTTP $code):"
  head -c 400 "$tmp"; echo
  rm -f "$tmp"
  if [ "$code" = "402" ]; then
    echo "The key is valid, but the account has no balance. Add credits, then rerun."
    open_url "https://platform.deepseek.com/top_up"
  elif [ "$code" = "401" ]; then
    echo "The key was not accepted. Create or copy a key on the API keys page (a key is separate from credits)."
    open_url "https://platform.deepseek.com/api_keys"
  fi
  echo "Key:     https://platform.deepseek.com/api_keys"
  echo "Credits: https://platform.deepseek.com/top_up"
  exit 1
fi
rm -f "$tmp"
echo "Key accepted."

# 4. Settings
settings="$HOME/.claude/settings.json"
mkdir -p "$HOME/.claude"
if [ -f "$settings" ]; then
  backup="$settings.bak-deepseek-$(date +%Y%m%d-%H%M%S)"
  cp "$settings" "$backup"
  echo "Existing settings backed up to $backup"
fi

if ! command -v python3 >/dev/null 2>&1; then
  echo "python3 is required to merge the settings file safely."
  echo "Install it, or add this block to $settings manually:"
  echo
  cat <<EOF
{
  "env": {
    "ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic",
    "ANTHROPIC_AUTH_TOKEN": "YOUR_KEY",
    "ANTHROPIC_MODEL": "deepseek-v4-flash",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "deepseek-v4-flash",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "deepseek-v4-flash",
    "CLAUDE_CODE_MAX_CONTEXT_TOKENS": "1000000"
  }
}
EOF
  exit 1
fi

read -rp "Add the recommended DeepSeek extras (effort max, subagent on V4 Flash, Opus alias, no non-essential traffic)? [y/N] " extras
extras="${extras:-n}"

python3 - "$settings" "$DEEPSEEK_API_KEY" "$extras" <<'PY'
import json, os, sys
path, key = sys.argv[1], sys.argv[2]
try:
    with open(path) as f:
        data = json.load(f)
except FileNotFoundError:
    data = {}
except Exception as e:
    sys.exit("settings.json is not valid JSON (%s). Fix or move it, then rerun." % e)
env = data.setdefault("env", {})
env.update({
    "ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic",
    "ANTHROPIC_AUTH_TOKEN": key,
    "ANTHROPIC_MODEL": "deepseek-v4-flash",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "deepseek-v4-flash",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "deepseek-v4-flash",
    "CLAUDE_CODE_MAX_CONTEXT_TOKENS": "1000000",
})
if len(sys.argv) > 3 and sys.argv[3].lower().startswith("y"):
    env.update({
        "ANTHROPIC_DEFAULT_OPUS_MODEL": "deepseek-v4-flash",
        "CLAUDE_CODE_SUBAGENT_MODEL": "deepseek-v4-flash",
        "CLAUDE_CODE_EFFORT_LEVEL": "max",
        "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
    })
with open(path, "w") as f:
    json.dump(data, f, indent=2)
os.chmod(path, 0o600)
print("Settings written to", path)
PY

read -rp "Create a starter CLAUDE.md in ~/.claude? [y/N] " starter
if [ "${starter:-n}" = "y" ] || [ "${starter:-n}" = "Y" ]; then
  if [ -f "$HOME/.claude/CLAUDE.md" ]; then
    echo "CLAUDE.md already exists; left alone."
  else
    cat > "$HOME/.claude/CLAUDE.md" <<'EOF'
# Working with me
- Be concise.
- Show the command before running anything destructive.
- Ask before deleting or overwriting files.
- If something fails, say what failed and why.
EOF
    echo "Starter CLAUDE.md created: $HOME/.claude/CLAUDE.md"
  fi
fi

if ! command -v git >/dev/null 2>&1; then
  echo "Optional: install Git for the Bash tool: https://git-scm.com/downloads"
fi
echo "Optional inside Claude Code: /plugin for plugins, /mcp for extra tools, /permissions for command approvals."

echo
echo "Done. Open a new terminal, cd to a project, and run: claude"
echo "First run: accept the theme and the folder-trust prompt."
